import { useEffect, useState, FC } from 'react'
import { getUsersList, updataUserInfo, logOff } from '@/request/user'
import { Space, Table, Popconfirm, message, Input, Modal, Tree } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import { getUserMenuList } from '@/request/basicSettings'
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
let userid: any = null
let current = 1
const Users: FC = () => {
    const columns: ColumnsType<any> = [
        {
            title: '头像',
            dataIndex: 'handimg',
            key: 'handimg',
            fixed: 'left',
            render: (_, record) => (
                <div>
                    <img style={{ width: '50px', height: '50px', borderRadius: '50%' }} src={record.handimg} />
                </div>
            )
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            fixed: 'left',
        },
        {
            title: '账号',
            dataIndex: 'account',
            key: 'account',
            fixed: 'left',
        },
        {
            title: '签名',
            dataIndex: 'sign',
            key: 'sign',
            render: (text) => (
                <div>{text ? text : '/'}</div>
            )
        },
        {
            title: '注册时间',
            dataIndex: 'createtime',
            key: 'createtime',
            render: (_, record) => (
                <div>{dayjs(record.createtime).format('YYYY-MM-DD')}</div>
            )
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            render: (text) => (
                <div>{text ? text : '/'}</div>
            )
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            render: (_, record) => {
                if (record.sex === 0) {
                    return (
                        <span>男</span>
                    )
                } else if (record.sex === 1) {
                    return (
                        <span>女</span>
                    )
                } else {
                    return (
                        <span>/</span>
                    )
                }
            }
        },
        {
            title: '生日',
            dataIndex: 'birthday',
            key: 'birthday',
            render: (_, record) => (
                <div>{record.birthday ? dayjs(record.birthday).format('YYYY-MM-DD') : '/'}</div>
            )
        },
        {
            title: '家乡',
            dataIndex: 'hometown',
            key: 'hometown',
            render: (text) => (
                <div>{text ? text : '/'}</div>
            )
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            render: (_, record) => (
                <Space size="middle">
                    <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record)}>
                        <a>注销</a>
                    </Popconfirm>
                    <a onClick={() => { edit(record) }}>权限</a>
                </Space>
            ),
        },
    ];
    const { Search } = Input
    const [checkedKeys, setCheckedKeys] = useState([])   //选中
    const [isModalOpen, setIsModalOpen] = useState(false);  //弹窗
    const [users, setUsers]: any = useState([]) //用户列表
    const [searchValue, setSearchValue]: any = useState(null) //搜索值
    // 分页
    const [pagination, setPagination]: any = useState({
        pageSize: 10,
        total: 0
    })
    // 权限菜单
    const [treeData, setTreeData]: any[] = useState([])

    // 获取导航
    const getUserMenu = async () => {
        const res = await getUserMenuList()
        setTreeData(res.data)
    }
    const getUserInfoList = async (value?: string, page?: number) => {
        const res: any = await getUsersList({
            page: page,
            pageSize: pagination.pageSize,
            searchValue: value
        })
        setUsers(res.data)
        setPagination({
            ...pagination,
            total: res.total
        })
    }
    const handleDelete = async (record: any) => {
        const res = await logOff({
            userid: record.userid
        })
        if (res.status === 200) {
            message.info('注销成功')
            getUserInfoList(searchValue, 1)
        }
    }
    const edit = (record: any) => {
        userid = record.userid
        if (record.auth) {
            let list = record.auth.split(',')
            list = list.map(Number)
            setCheckedKeys(list)
        }

        setIsModalOpen(true)
    }
    const onChange = (page: number) => {
        current = page
        getUserInfoList(searchValue, page)
    }
    const onSearch = (value: string) => {
        setSearchValue(value)
        getUserInfoList(value, 1)
    }
    const handleOk = async () => {
        const res = await updataUserInfo({
            auth: checkedKeys.join(','),
            userid: userid
        })
        if (res.status === 200) {
            setCheckedKeys([])
            setIsModalOpen(false);
            message.info('设置成功')
            getUserInfoList(searchValue, current)
        }
    }
    const onCancel = () => {
        setCheckedKeys([])
        setIsModalOpen(false)
    }
    useEffect(() => {
        getUserMenu()
        getUserInfoList(searchValue, 1)
    }, [])
    const onCheck: TreeProps['onCheck'] = (keys: any) => {
        setCheckedKeys(keys)
    };
    return (
        <div>
            <div>
                <Search placeholder="用户名/账号" onSearch={onSearch} style={{ width: 200 }} />
            </div>
            <Table columns={columns} dataSource={users} rowKey="userid" pagination={{
                ...pagination,
                showQuickJumper: true,
                onChange: onChange
            }} />
            <Modal title="权限设置" open={isModalOpen}
                onOk={handleOk} onCancel={onCancel}
            >
                <div style={{ height: '50vh', overflowY: "scroll", margin: '20px 0' }}>
                    <Tree
                        checkable
                        defaultExpandAll
                        onCheck={onCheck}
                        treeData={treeData}
                        checkedKeys={checkedKeys}
                        fieldNames={{
                            title: 'label',
                            key: 'id'
                        }}
                    />
                </div>
            </Modal>
        </div>
    )
}
export default Users
